package com.lagou.edu.service.impl;

import com.lagou.edu.fegin.MailClient;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.util.CodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class CodeServiceImpl implements CodeService {

    private static final String USER_REGISTER_CODE = "USER:REGISTER:CODE";

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    MailClient mailClient;

    @Override
    public boolean getCode(String email) {
        //1.随机生成一个6位数字的验证码
        String code = CodeUtil.generateCode();
        log.info("验证码为："+code);
        //2.将Map<email,验证码>保存到redis中，有效时间设为3分钟
        redisTemplate.opsForHash().put(USER_REGISTER_CODE, email, code);
        redisTemplate.expire(USER_REGISTER_CODE,3, TimeUnit.MINUTES);
        //3.向用户邮箱发送邮件
        String subject="用户登录系统";
        String content="用户你好，你的验证码为："+code+"，有效时间3分钟";
        try {
            mailClient.sendMail(email, subject, content);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
